/********************************************************************************************************
 * PROGRAM      : MPodConTMReader
 * DATE - TIME  : 
 * AUTHOR       :  ( Daniel Kish )
 * FILENAME     : mpodcontmreader.cpp
 * LICENSE      : 
 * COMMENTARY   : 
 ********************************************************************************************************/

#include "mpodcontmreader.h"
namespace TM {

MPodConTMReader::MPodConTMReader(const QString &sPort,QObject *parent): MDataReader(sPort, parent)
{
}


MPodConTMReader::~MPodConTMReader()
{
}

/*!
    \fn MPodConTMReader::readTM()
    Pure virtual implementation: Reads the PodCon telemetry from the serial port
    (used in MTelemetry)
 */

MDataBlock* MPodConTMReader::readTM() throw(MException)
{
  MDataBlock *block = NULL;

  MDataBlock::TYPE type = MDataBlock::ERR;
  sync();
   while(m_serial->bytesAvailable() <  sizeof(MDataBlock))
   {
    msleep(100);
   }
    qDebug()<<"CamCon block";
  if(m_serial->bytesAvailable() >= sizeof(MDataBlock))
  {
   //qDebug()<<"before allocation"<<" bytes:"<<m_serial->bytesAvailable()<<"sizeof:"<<sizeof(MDataBlock);
   block = new MDataBlock(MDataBlock::PODCON);
   //qDebug()<<"after allocation";
   m_serial->readData((char*)block,sizeof(MDataBlock));
   qDebug()<<(int)block->blockNum();
   msleep(1);
  } 
  qDebug()<<"returning";
  return block;  
}




/*!
    \fn TM::MPodConTMReader::sync()
 */
void TM::MPodConTMReader::sync()
{
    unsigned char temp=0;
    int i;
    qDebug()<<"syncing...";
    while(1)
    {
     i=0;
     if(m_serial->bytesAvailable()>4)
       if( m_serial->getChar((char*)&temp) && temp==0xa5 )
       {
        //qDebug("-%x",temp);
        for(i=0;i<(SYNC_SIZE-1) && temp == 0xa5;++i)
        {
         m_serial->getChar((char*)&temp);
         msleep(10);
         if(temp !=0xa5) break;
         //qDebug("--%x i:%d",temp,i);
        }
       }
     //else  qDebug("---%x",temp);
     if(i==(SYNC_SIZE-1) ) break;
     msleep(100);
    }
}



}